//
//  HORepairerListViewController.m
//  微度报修
//
//  Created by foguo-mac-1 on 7/4/16.
//  Copyright © 2016 WeiDu. All rights reserved.
//

#import "HORepairerListViewController.h"
#import "HORepairerEntity.h"
#import "HOConstants.h"
#import "UIImageView+WebCache.h"
#import "HOImageMgr.h"
#import "HOUtils.h"
#import "HOButton.h"
#import "HORepairerDetailViewController.h"
#import "HOStaticDataMgr.h"
#import "HOFaultCategoryViewController.h"

@interface HORepairerListViewController ()<HOFaultCategoryViewControllerDelegate>

@property(nonatomic, retain)HODepartmentEntity *selectedDepartmentEntity;
@property(nonatomic, retain)NSMutableArray *departmentList;
@end

@implementation HORepairerListViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view.
	[self initDataSource];
	[self initTableView];
	[self requestData];
}

- (void)dealloc
{
	[self.departmentList removeAllObjects];
	self.departmentList = nil;
	self.delegate = nil;
	self.selectedDepartmentEntity = nil;
	[super dealloc];
}

- (void)initDataSource
{
	self.departmentList = [NSMutableArray array];
}

- (void)requestData
{
	[self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_GetRepairmanList,
								  kHO_FIELD_DepartmentId:[NSNumber numberWithInt:self.departmentId]}];
	
	[self sendRequestWithParams:@{kHO_FIELD_Action:kHO_ACTION_Department,
								  kHO_FIELD_MaxID:[NSNumber numberWithInt:0]}];
}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	[self setNavigationItemTitle:NSLocalizedString(@"添加维修协助人", @"添加维修协助人")];
	self.tabBarController.tabBar.hidden = YES;
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}
#pragma mark - -- UITableViewDelegate/UITableViewDataResource implement methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(indexPath.section == 0)
	{
		return 60;
	}
	else
	{
		return CELL_HEIGHT;
	}
	return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	if(section == 0)
	{
		NSInteger repairerCount = [self.tableViewDataList count];
		return repairerCount;
	}
	else
	{
		NSInteger departmentCount = [self.departmentList count];
		return departmentCount;
	}
	return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 30)] autorelease];
	UILabel *lbl = [[[UILabel alloc] initWithFrame:CGRectMake(HO_HORIZONAL_PADDING, 4, tableView.frame.size.width, 22)] autorelease];
	lbl.font = [UIFont systemFontOfSize:15];
	lbl.textColor = TEXT_GRAY_DARK_COLOR;
	if(section == 0)
	{
		lbl.text = @"添加本科室维修人员";
	}
	else if(section == 1)
	{
		lbl.text = @"添加其他科室";
		
	}
	[view addSubview:lbl];
	return view;
	
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if(indexPath.section == 0)
	{
		
		static NSString *UIRepairerTableViewCell = @"UIRepairerTableViewCell";
		UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:UIRepairerTableViewCell];
		if(cell == nil)
		{
			cell = [[[UITableViewCell alloc]
					 initWithStyle:UITableViewCellStyleDefault
					 reuseIdentifier: UIRepairerTableViewCell] autorelease];
		}
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		HORepairerEntity *entity = [self.tableViewDataList objectAtIndex:indexPath.row];
		UIImageView *headerImgView = (UIImageView *)[cell viewWithTag:112];
		if(headerImgView == nil)
		{
			headerImgView = [[[UIImageView alloc]
							  initWithFrame:CGRectMake(HO_HORIZONAL_PADDING,
													   7,
													   34,
													   34)] autorelease];
			headerImgView.tag = 112;
			[headerImgView.layer setCornerRadius:17];
			[cell.contentView addSubview:headerImgView];
			[headerImgView.layer setMasksToBounds:YES];
		}
		
		
		[headerImgView sd_setImageWithURL:[NSURL URLWithString:entity.headPic] placeholderImage:[[HOImageMgr sharedInstance] getDefaultImage]];
		
		
		
		UILabel *workStatusLbl = (UILabel *)[cell viewWithTag:1123];
		if(workStatusLbl == nil)
		{
			workStatusLbl = [[[UILabel alloc]
							  initWithFrame:CGRectMake(12,
													   38,
													   40,
													   22)] autorelease];
			workStatusLbl.tag = 1123;
			[cell.contentView addSubview:workStatusLbl];
			workStatusLbl.textColor = TEXT_COLOR_181818;
			workStatusLbl.font = [UIFont systemFontOfSize:12];
		}
		if(entity.isWorking)
		{
			workStatusLbl.text = @"[在线]";
			workStatusLbl.textColor = UIColorFromRGB(0x0b7f1e);
		}
		else
		{
			workStatusLbl.text = @"[离线]";
			workStatusLbl.textColor = UIColorFromRGB(0xcdcdcd);
		}
		
		UILabel *nameLbl = (UILabel *)[cell viewWithTag:115];
		if(nameLbl == nil)
		{
			nameLbl = [[[UILabel alloc]
						initWithFrame:CGRectMake(54,
												 8,
												 [HOUtils getScreenSize].width - 115,
												 22)] autorelease];
			nameLbl.tag = 115;
			[cell.contentView addSubview:nameLbl];
			nameLbl.textColor = TEXT_COLOR_181818;
			//		nameLbl.layer.borderWidth = 1;
			nameLbl.font = [UIFont systemFontOfSize:14];
		}
		//	nameLbl.text = entity.userName;
		NSString *name = [HOUtils getTrimingString:entity.HopeName];
		if(name.length == 0)
		{
			name = entity.userName;
		}
		
		nameLbl.text = name;
		CGSize contentSize = CGSizeZero;//时间文字宽度
		if(IS_LESSTHAN_IOS7)
		{
			contentSize = [entity.userName sizeWithFont:[UIFont systemFontOfSize:12.0]];
		}
		else
		{
			contentSize = [entity.userName sizeWithAttributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:15]}];
		}
		nameLbl.frame = CGRectMake(54,
								   8,
								   [HOUtils getScreenSize].width - 240,
								   22);
		
		UILabel *levelLbl = (UILabel *)[cell viewWithTag:116];
		if(levelLbl == nil)
		{
			levelLbl = [[[UILabel alloc]
						 initWithFrame:CGRectMake(120,
												  8,
												  80,
												  22)] autorelease];
			levelLbl.tag = 116;
			[cell.contentView addSubview:levelLbl];
			levelLbl.textColor = TEXT_COLOR_181818;
			levelLbl.font = [UIFont systemFontOfSize:13];
		}
		levelLbl.text = entity.level;
		
		levelLbl.frame = CGRectMake(nameLbl.frame.origin.x + nameLbl.frame.size.width + HO_HORIZONAL_PADDING + 35,
									8,
									100,
									22);
		
		
		UILabel *ratingLlb = (UILabel *)[cell viewWithTag:117];
		if(ratingLlb == nil)
		{
			ratingLlb = [[[UILabel alloc]
						  initWithFrame:CGRectMake(nameLbl.frame.origin.x,
												   32,
												   200,
												   22)] autorelease];
			ratingLlb.tag = 117;
			[cell.contentView addSubview:ratingLlb];
			ratingLlb.textColor = TEXT_COLOR_666666;
			ratingLlb.font = [UIFont systemFontOfSize:13];
		}
		int apprise = ((int)(entity.appraise + 1));
		ratingLlb.text = [NSString stringWithFormat:@"%@ %d", NSLocalizedString(@"评分：", @"评分："), (apprise, 5)];
		
		HOButton *iconImgView = (HOButton *)[cell viewWithTag:118];
		if(iconImgView == nil)
		{
			UIImage *image = [UIImage imageNamed:@"ic-chakanzhuangtai_dadianhua"];
			iconImgView = [[[HOButton alloc]
							initWithFrame:CGRectMake(135,
													 (60 - 35) / 2,
													 35,
													 35)] autorelease];
			iconImgView.tag = 118;
			[iconImgView setBackgroundImage:image forState:UIControlStateNormal];
			//			iconImgView.layer.borderWidth = 1;
			[iconImgView addTarget:self action:@selector(callPhoneNumber:) forControlEvents:UIControlEventTouchUpInside];
			[cell.contentView addSubview:iconImgView];
		}
//		if(entity.virtualCellPhone == nil || entity.virtualCellPhone.length < 2)
//		{
//			iconImgView.hidden = YES;
//		}
//		else
//		{
//			iconImgView.hidden = NO;
//		}
		iconImgView.data = entity;
		
		HOButton *btn = (HOButton *)[cell viewWithTag:554];
		if(btn == nil)
		{
			btn = [[[HOButton alloc]
					initWithFrame:CGRectMake(tableView.frame.size.width - 110,
											 (60 - 30) / 2,
											 80,
											 30)] autorelease];
			btn.tag = 554;
			[btn setTitle:NSLocalizedString(@"查看详情", @"查看详情") forState:UIControlStateNormal];
			[btn setTitleColor:TEXT_COLOR_181818 forState:UIControlStateNormal];
			btn.titleLabel.font = [UIFont systemFontOfSize:14];
			btn.layer.borderWidth = [HOUtils defaultOnePixelConversion];
			btn.layer.cornerRadius = 5;
			[btn.layer setMasksToBounds:YES];
			[btn addTarget:self action:@selector(viewDetail:) forControlEvents:UIControlEventTouchUpInside];
			[cell.contentView addSubview:btn];
		}
		btn.data = entity;
		return cell;
	}
	else if(indexPath.section == 1)
	{
		static NSString *AMBaseTableViewCellIdentifier = @"HOTableViewCell";
		HOTableViewCell *cell = (HOTableViewCell *)[tableView dequeueReusableCellWithIdentifier:AMBaseTableViewCellIdentifier];
		if(cell == nil)
		{
			cell = [[[HOTableViewCell alloc]
					 initWithStyle:UITableViewCellStyleDefault
					 reuseIdentifier: AMBaseTableViewCellIdentifier] autorelease];
		}
		HODepartmentEntity *entity = [self.departmentList objectAtIndex:indexPath.row];
		cell.textLabel.text = entity.departmentName;
		cell.textLabel.font = [UIFont systemFontOfSize:15];
		cell.textLabel.textColor = TEXT_COLOR_181818;
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		cell.selectionStyle = UITableViewCellSelectionStyleGray;
		return cell;
	}
	return nil;
}

- (void)callPhoneNumber:(id)sender
{
	HOButton *btn = (HOButton *)sender;
	HORepairerEntity *entity = (HORepairerEntity *)btn.data;
	
	[HOUtils callPhoneNumber:entity.virtualCellPhone];
}

- (void)viewDetail:(HOButton *)btn
{
	HORepairerEntity *entity = btn.data;
	HORepairerDetailViewController *viewCtrl = [[HORepairerDetailViewController alloc] init];
	viewCtrl.userId = entity.userId;
	viewCtrl.isWorking = entity.isWorking;
	[self.navigationController pushViewController:viewCtrl animated:YES];
	[viewCtrl release];
	
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	if(indexPath.section == 0)
	{
		HORepairerEntity *entity = [self.tableViewDataList objectAtIndex:indexPath.row];
		[self goBack];
		[self.delegate didSelectRepairer:entity withDepartment:nil withFaultType:nil withFaultType:nil];
	}
	else if(indexPath.section == 1)
	{
		self.selectedDepartmentEntity = [self.departmentList objectAtIndex:indexPath.row];
		
		HOFaultCategoryViewController *viewCtrl = [[HOFaultCategoryViewController alloc] init];
		viewCtrl.delegate = self;
		viewCtrl.departmentId = self.selectedDepartmentEntity.departmentId;
		[self.navigationController pushViewController:viewCtrl animated:YES];
		[viewCtrl release];
	}
	
}

- (void)didSelectFault:(HOFaultCategoryEntity *)entity withSubEntity:(HOFaultCategoryEntity *)subEntity
{
	if(entity == nil || subEntity == nil)
	{
		[self popupHintView:@"选择内容出错，请重新选择"];
		return;
	}
	[self goBack];
	[self.delegate didSelectRepairer:nil withDepartment:self.selectedDepartmentEntity withFaultType:entity withFaultType:subEntity];
}
#pragma mark - -- tool


- (void)requestDidSuccessWithResponse:(HOBaseResponseEntity *)response
{
	if([response isEqualAction:kHO_ACTION_GetRepairmanList])
	{
		[self.tableViewDataList removeAllObjects];
		for(int i = 0; i < [response.dataNode count]; i ++)
		{
			HORepairerEntity *entity = [[HORepairerEntity alloc] init];
			[entity parseDic:[response.dataNode objectAtIndex:i]];
			NSNumber *uid = [NSNumber numberWithInt:entity.userId];
			if(![self.assistantIdList containsObject:uid])
			{
				[self.tableViewDataList addObject:entity];
			}
			[entity release];
		}
		[baseTableview reloadData];
	}
	else if([response isEqualAction:kHO_ACTION_Department])
	{
		[self.departmentList removeAllObjects];
		if(![response.dataNode isKindOfClass:[NSArray class]])
		{
			return;
		}
		[[HOStaticDataMgr sharedInstance] didReceiveDepartmentList:response.dataNode];
		for(int i = 0; i <  [[HOStaticDataMgr sharedInstance].departmentList count]; i ++)
		{
			HODepartmentEntity *departmentEntity =  [[HOStaticDataMgr sharedInstance].departmentList objectAtIndex:i];
			NSNumber *uid = [NSNumber numberWithInt:departmentEntity.departmentId];
			if(![self.assistantIdList containsObject:uid])
			{
				[self.departmentList addObject:departmentEntity];
			}
			
		}
		[baseTableview reloadData];
	}
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

